﻿@model FileInfo[]
@{
    Layout = "~/Views/Shared/_Layout.cshtml";
    string ontologyCode = Request.Params["ontologyCode"];
    var ontology = Html.GetOntology(ontologyCode);
    var elements = ontology.Elements.Values.Where(e => e.Element.IsGridColumn).OrderBy(e => e.Element.SortCode);
    ViewBag.Title = "导入" + ontology.Ontology.Name;
}
@section Head{
    <style type="text/css">
        .fileDiv {
            cursor: pointer;
        }

        .hover {
            background: #E5F3F5;
        }

        .clicked {
            background: #D1E8FF;
        }
    </style>
}
<div id="splitter" class="mini-splitter helperSplitter" style="width: 100%; height: 100%;">
    <div size="430" showcollapsebutton="true">
        <div class="mini-toolbar" style="border: 0; padding: 2px;">
            <div style="float: left">
                <div>
                    <a id="btnDelete" class="mini-button" @Html.IsEnabled("Entity", "DeleteFile")>删除</a>
                    <span id="msg" style="color: red;">@TempData["Message"]</span>
                </div>
            </div>
            <div style="float: right">
                <form id="fileForm" action="Import?ontologyCode=@ontologyCode" method="post" enctype="multipart/form-data">
                    <input id="htmlFile" class="mini-htmlfile" name="fileData" width="200px" limittype="*.xls" />
                    <a id="btnSubmit" class="mini-button" type="submit">上传</a>
                    <a id="btnTemplate" class="mini-button" @Html.IsEnabled("Entity", "DownloadTemplate")>模板</a>
                    @{
                        CatalogState r;
                        if (!Html.CurrentHost().CatalogSet.TryGetCatalog(Html.CurrentHost().AppSystemSet.SelfAppSystem.Code +"." + "InfoDic", out r)) {
                            throw new Anycmd.Exceptions.GeneralException("意外的资源码");
                        }
                    }
                    <a id="btnInfoDicItem" class="mini-button" target="_blank" plain="true">
                        @r.Name
                    </a>
                </form>
            </div>
            <div style="clear: both;">
            </div>
        </div>
        <!--撑满页面-->
        <div class="mini-fit">
            <div id="dgFiles" class="mini-datagrid" style="width:100%;height:100%;" allowalternating="true"
                 url="@Url.Action("GetFiles", new { ontologyCode = ontology.Ontology.Code })" idfield="Id" multiselect="true" showmodified="false" showpager="false">
                <div property="columns">
                    <div type="indexcolumn"></div>
                    <div type="checkcolumn"></div>
                    <div name="action" width="30" headeralign="center" align="center" cellstyle="padding:0;">
                    </div>
                    <div field="Name" width="170" headeralign="center" allowsort="false">
                        文件名
                    </div>
                    <div field="UserName" width="60" headeralign="center" allowsort="false">
                        用户
                    </div>
                    <div field="CreationTime" width="140" headeralign="center" dateformat="yyyy-MM-dd HH:mm:ss" allowsort="false">
                        导入时间
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div showcollapsebutton="true">
        <div class="mini-toolbar" style="border: 0; padding: 2px;">
            <div style="float: left">
                <a id="btnDownload" class="mini-button" @Html.IsEnabled("Entity", "DownloadResult")>下载结果</a>
                <span style="color: red;">注意：服务器不会长久保存用户上传的Excel文件。</span>
            </div>
            <div style="float: right">
            </div>
            <div style="clear: both;">
            </div>
        </div>
        <!--撑满页面-->
        <div class="mini-fit">
            <div id="datagrid1" class="mini-datagrid" style="width:100%;height:100%;" allowalternating="true" allowcellwrap="true"
                 url="@Url.Action("GetFileRows", new { ontologyCode = ontologyCode })" idfield="Id" multiselect="true"
                 idfield="Id" multiselect="true" showpager="false">
                <div property="columns">
                </div>
            </div>
        </div>
    </div>
</div>
@{Html.RenderPartial("Partials/ImportElement", ontology);}
@section Foot{
    <script type="text/javascript">
        mini.parse();

        var btnDelete = mini.get("btnDelete");
        btnDelete.on("click", function () {
            var records = dgFiles.getSelecteds();
            if (records.length > 0) {
                mini.confirm("确定删除选中记录？", "确定？", function (action) {
                    if (action == "ok") {
                        remove(records);
                    }
                });
            } else {
                mini.showTips({
                    content: "没有选中记录",
                    state: "warning",
                    x: "center",
                    y: "top",
                    timeout: 3000
                });
            }
        });
        var btnSubmit = mini.get("btnSubmit");
        btnSubmit.on("click", function () {
            helper.requesting("处理批量导入可能会耗费一段时间，请耐心等待。");
            $("#fileForm").get(0).submit();
        });
        var btnInfoDicItem = mini.get("btnInfoDicItem");
        if (window.top.topShowTab) {
            btnInfoDicItem.on("click", function () {
                var tab = {};
                tab.text = "信息字典";
                tab.url = bootPATH + '../Edi/InfoDic/Index';
                window.top.topShowTab(tab);
            });
        }
        else {
            btnInfoDicItem.setHref(bootPATH + '../Edi/InfoDic/Index');
        }
        var dgFiles = mini.get("dgFiles");
        var datagrid1 = mini.get("datagrid1");
        dgFiles.on("drawcell", dgFilesDrawcell);
        dgFiles.on("load", helper.onGridLoad);
        datagrid1.on("drawcell", drawcell);
        window.remove = remove;
        function dgFilesDrawcell(e) {
            var field = e.field;
            var value = e.value;
            var columnName = e.column.name;
            if (columnName && columnName == "action") {
                var record = e.record;
                var html = "";
                html += '&nbsp;&nbsp;<a title="删除" href="javascript:remove(\'' + record.Id + '\')"><img alt="删除" border="0" src="' + bootPATH + '../Scripts/miniui/themes/icons/remove.gif" /></a>';
                if (html) {
                    e.cellHtml = html;
                }
            }
        };
        function drawcell(e) {
            var field = e.field;
            var value = e.value;
            if (field) {
                switch (field) {
                    case "$StateCode":
                        var v = parseInt(value);
                        if (v != NaN && (v < 200 || v >= 300)) {
                            e.rowStyle = "background:#FF9900;";
                        }
                        break;
                }
            }
        };
        dgFiles.on("selectionchanged", function (e) {
            var record = dgFiles.getSelected();
            if (!record || dgFiles.getSelecteds().length > 1) {
                datagrid1.clearRows();
            }
            else {
                $.get("GetColumns", { ontologyCode: '@ontology.Ontology.Code', fileName: record.Id }, function (result) {
                    datagrid1.set(result);
                    datagrid1.load({ fileName: record.Id });
                });
            }
        });

        dgFiles.load();
        var btnTemplate = mini.get("btnTemplate");
        var import_win1 = mini.get("import_win1");
        btnTemplate.on("click", function (e) {
            import_win1.show();
        });
        var cblImportElement = mini.get("cblImportElement");
        var btnDownloadTemplate = mini.get("btnDownloadTemplate");
        btnDownloadTemplate.on("click", function (e) {
            downloadTemplate(cblImportElement.getValue());
        });
        var htmlFile = mini.get("htmlFile");
        htmlFile.on("fileselect", function (e) {
            var fileName = htmlFile.getValue();
            var extensionName = ".xls";
            var el = extensionName.length;
            if (!fileName || fileName.length <= el || fileName.substring(fileName.length - el) != extensionName) {
                $("#msg").text('"' + fileName + '"' + "是不支持的excel文件");
                $("#btnSubmit").hide();
            }
            else {
                $("#msg").text("");
                $("#btnSubmit").show();
            }
        });
        var btnDownload = mini.get("btnDownload");
        btnDownload.on("click", function (e) {
            var record = dgFiles.getSelected();
            if (record) {
                var submitfrm = document.createElement("form");
                submitfrm.action = "DownloadResult";
                submitfrm.method = "post";
                submitfrm.target = "_blank";
                document.body.appendChild(submitfrm);

                var ontologyInput = mini.append(submitfrm, "<input type='hidden' name='ontologyCode'>");
                ontologyInput.value = '@ontology.Ontology.Code';
                var fileNameInput = mini.append(submitfrm, "<input type='hidden' name='fileName'>");
                fileNameInput.value = record.Id;

                submitfrm.submit();
                setTimeout(function () {
                    submitfrm.parentNode.removeChild(submitfrm);
                    import_win1.hide();
                }, 1000);
            }
            else {
                mini.showTips({
                    content: "请选中一次导入记录",
                    state: "warning",
                    x: "center",
                    y: "top",
                    timeout: 3000
                });
            }
        });
        function downloadTemplate(elements) {
            var submitfrm = document.createElement("form");
            submitfrm.action = "DownloadTemplate";
            submitfrm.method = "post";
            submitfrm.target = "_blank";
            document.body.appendChild(submitfrm);

            var ontologyInput = mini.append(submitfrm, "<input type='hidden' name='ontologyCode'>");
            ontologyInput.value = '@ontology.Ontology.Code';
            var elementsInput = mini.append(submitfrm, "<input type='hidden' name='elements'>");
            elementsInput.value = elements;

            submitfrm.submit();
            setTimeout(function () {
                submitfrm.parentNode.removeChild(submitfrm);
                import_win1.hide();
            }, 1000);
        }
        function directRemove(fileNames) {
            if (fileNames) {
                dgFiles.loading("操作中，请稍后......");
                $.post("DeleteFile", { fileNames: fileNames, ontologyCode: '@ontology.Ontology.Code' }, function (result) {
                    helper.response(result, function () {
                        dgFiles.reload();
                        datagrid1.clearRows();
                    }, function () {
                        dgFiles.unmask();
                    });
                }, "json");
            }
        };
        function remove(records) {
            var id;
            if (typeof records == typeof []) {
                var ids = [];
                for (var i = 0, l = records.length; i < l; i++) {
                    var r = records[i];
                    ids.push(r.Id);
                }
                id = ids.join('/');
                directRemove(id);
            }
            else {
                mini.confirm("确定删除选中记录？", "确定？", function (action) {
                    if (action == "ok") {
                        if (typeof records == "string") {
                            id = records;
                        }
                        else if (records && records.Id) {
                            id = records.Id;
                        }
                        directRemove(id);
                    }
                });
            }
        };
    </script>
}
